package vin.pth.authorization.token;


import java.util.ArrayList;
import java.util.Collection;
import lombok.Getter;
import vin.pth.base.pojo.Authentication;
import vin.pth.base.pojo.GrantedAuthority;
import vin.pth.base.pojo.UserDetails;

/**
 * 用户名密码的令牌.
 *
 * @author cocoon
 */
@Getter
public class UsernamePasswordToken implements Authentication {

  private final String username;
  private final String password;
  private final boolean authenticated;
  private final UserDetails userDetails;

  /**
   * 用于管理认证通过或者不通过.
   *
   * @param userDetails   封装的用户详情
   * @param authenticated 是否认证通过
   */
  public UsernamePasswordToken(UserDetails userDetails, boolean authenticated) {
    this.username = userDetails.getUsername();
    this.password = userDetails.getPassword();
    this.userDetails = userDetails;
    this.authenticated = authenticated;
  }

  @Override
  public String getPrincipal() {
    return username;
  }

  @Override
  public String getCredentials() {
    return password;
  }

  /**
   * 用户具备的权限.
   *
   * @return GrantedAuthority
   */
  @Override
  public Collection<? extends GrantedAuthority> getAuthorities() {
    if (this.userDetails == null) {
      return new ArrayList<>();
    }
    return userDetails.getAuthority();
  }

}
